
var defaultParameter = {
    pageNumber: 1,
    pageSize: 20
};

var succTendInfoList;

function initTable(){

    var columns=[[
        {field:'impleProjId',title:'项目id',fitColumns:true,hidden:true,
            formatter: function(value,row,index){
                return row.implementProject.impleProjId;
            }},
        {field:'impleProjName',title:'实施项目名称',width:120,fitColumns:true,
            formatter: function(value,row,index){
                return row.implementProject.impleProjName;
            }},
        /*
         {field:'orgId',title:'建设单位',width:120,fitColumns:true,
         formatter: function(value,row,index){
         return row.implementProject.developOrgName;
         }},
         */
        {field:'purchPlanId',title:"采购计划id",fitColumns:true,hidden:true,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null){
                    return row.purchasePlan.purchPlanId;
                }else{
                    return "";
                }
            }},
        {field:'purchPlanCode',title:"采购计划号",width:120,fitColumns:true,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null){
                    return "【" + row.purchasePlan.purchPlanNum + "】" + row.purchasePlan.purchPlanName;
                    //return "【" + row.purchasePlan.purchPlanCode + "】" + row.purchasePlan.purchPlanName;
                }else{
                    return "";
                }
            }},
        {field:'purchWayName',title:"采购方式",width:120,fitColumns:true,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null){
                    return row.purchasePlan.purchWayName;
                }else{
                    return "";
                }
            }},
        {field:'purchWay',title:"预算金额<br/>（万元）",width:80,fitColumns:true,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null){
                    return row.purchasePlan.prepayTotal;
                }else{
                    return "";
                }
            }},
        {field:'agentName',title:"采购代理机构",width:80,fitColumns:true,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null){
                    return row.purchasePlan.agentName;
                }else{
                    return "";
                }
            }},
        {field:'tenderTitle',title:"标书名称",width:150,fitColumns:true,
            formatter: function(value,row,index){
                if(row.docManage!=null){
                    return "【"+row.docManage.docCode +"】"+ row.docManage.docName;
                }else{
                    return "";
                }
            }},
        {field:'finalDt',title:'标书定稿时间',width:80,fitColumns:true,
            formatter: function(value,row,index) {
                if(row.docManage!=null){
                    return row.docManage.finalDt;
                }else{
                    return "";
                }
            }},
        {field:'startDt',title:'开标时间',width:80,fitColumns:true,
            formatter: function(value,row,index) {
                if(row.resultVo != null) {
                    return row.resultVo.openDt;
                }else{
                    return "";
                }
            }},
        {field:'person',title:"参与人员",width:60,fitColumns:true,
            formatter: function(value,row,index){
                var reviewer="";
                for(var i=0;i<row.evalBidPartyVos.length;i++){
                    reviewer+=row.evalBidPartyVos[i].reviewerName+",";
                }
                return reviewer.substring(0, reviewer.length - 1);
                // return row.evalBidPartyVo.reviewerName;
            }},
        {field:'description',title:"备注",width:150,fitColumns:true,
            formatter: function(value,row,index){
                if(row.tenderInfo!=null){
                    return row.tenderInfo.description;
                }else{
                    return "";
                }
            }
        },
        {field:'statusCd',title:"状态",width:60,fitColumns:true,
            formatter: function(value,row,index){
                return row.tenderInfo.statusName;
            }},
        {field:'operation',title:"操作",width:50,
            formatter: function(value,row,index){
                return '<a class="edit" href="javascript:void(0)" title="编辑" onclick="updateInvitModel('+ index+ ')"> <i class="fa fa-edit"></i></a>';
//            +'<a class="remove" href="javascript:void(0)" title="删除" onclick="delInvitConfirm('+ index+ ')"><i class="fa fa-trash"></i></a>';
            }},
    ]];

    $('#tenderList').datagrid({
        url:'/InfoManageWeb/tenderPreparationService/queryInviteInfo',
        method:'post',
        dataType : 'json',
        queryParams:defaultParameter,
        pagination:true,
        nowrap:false,
        fitColumns:true,
        columns:columns,
        loadFilter:function(data){
            if(data.resultCode!=0){
                toastr.error(data.resultMsg);
                return null;
            }else{
                return data.result;
            }
        },
    });
    var p = $('#tenderList').datagrid('getPager');
    $(p).pagination({
        pageSize: 20,//每页显示的记录条数，默认为10
        pageList: [10,20,30],//可以设置每页记录条数的列表
        beforePageText: '第',//页数文本框前显示的汉字
        afterPageText: '页    共 {pages}  页',
        displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
        onSelectPage:function(pageNumber, pageSize){
            defaultParameter.pageNumber=pageNumber;
            defaultParameter.pageSize=pageSize;
            defaultParameter.projectId=$("#implProjectId").val().trim();
            defaultParameter.planProjClass=$("#planProjClass").val().trim();
//      defaultParameter.docName=$("#docName").val().trim();
            defaultParameter.orgId=$("#orgId").val();
            $('#tenderList').datagrid('reload',defaultParameter);
        }
    });
}

function updateInvitModel(index){
    var row = $('#tenderList').datagrid('getData').rows[index];
    $('#addEditModal').modal("show").find('.modal-title').html('开标登记修改');
    $("#tenderInfoId").val(row.tenderInfo.tenderInfoId);
    $("#statusCd").val(row.tenderInfo.statusCd).trigger("change");
    //_callBackProjectInfo(row.implementProject.impleProjId,row.implementProject.impleProjName);
    if(row.resultVo!=null){
        $("#openDt").val(row.resultVo.openDt);
    }

    $('#docId').children().remove();
    $('#projectName').children().remove();
    $('#purchPlanName').children().remove();
    if(row.docManage != null) {
        $('#docId').append("<option value=" + row.docManage.docManageId + ">" + row.docManage.docName + "</option>");
    } else {
        $('#docId').append("<option value=''>无</option>");
    }
    if(row.implementProject!=null){
        $('#projectName').append("<option value=" + row.implementProject.impleProjId + ">" + row.implementProject.impleProjName + "</option>");
    }else {
        $('#projectName').append("<option value=''>无</option>");
    }
    if(row.purchasePlan != null) {
        $('#purchPlanName').append("<option value=" + row.purchasePlan.purchPlanId + ">" + row.purchasePlan.purchPlanName + "</option>");
    }else {
        $('#purchPlanName').append("<option value=''>无</option>");
    }

    var staffId="";
    var staffNames="";
    for(var i=0;i<row.evalBidPartyVos.length;i++){
        staffNames+=row.evalBidPartyVos[i].reviewerName+",";
        staffId+=row.evalBidPartyVos[i].reviewer+",";

    }
    if (row.evalBidPartyVos.length == 0) {
        staffId =row.implementProject.linkman;
        staffNames =row.implementProject.linkmanName;
    }
    $("#staffId").val(staffId);
    $("#reviewer").val(staffNames);
    $("#description").val(row.tenderInfo.description);

    //$("#orgList").val(row.resultVo.orgId);
    //$("#orgText").val(row.resultVo.orgName);


}

function delInvitConfirm(index){
    var row=$('#tenderList').datagrid('getData').rows[index];
    var param={};
    param.tenderInfoId=row.tenderInfo.tenderInfoId;
    com.im.common.confirm('确认删除？',param,"delTenderInfo");
}

function delTenderInfo(param){
    url = "/tenderPreparationService/deleteResultInfo";
    var client = new com.im.common.ajax();
    var result = client.callAsJson(url,param);
    if(!result.success) {
        toastr.error(result.resultMsg);
    }else{
        queryBidResultInfo();
    }
}

//作废
function _callBackProjectInfo(projectId,projectName){
    $("#projectName").val(projectId);
    //根据项目id获取采购计划
    $("#purchPlanName").empty();
    var client = new com.im.common.ajax();
    var param={
        "impleProjId":projectId,
    }
    var result = client.callAsJson("purchaseService/queryPurchasePlanByParam",param);

    console.log(result);
    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        result.result.unshift({'purchPlanId':'','purchPlanName':'全部'});
        $.each( result.result, function (i) {
            $('#purchPlanName').append("<option value=" + result.result[i].purchPlanId + ">" +result.result[i].purchPlanName + "</option>");

        });
        $("#purchPlanName").select2({});
        $("#purchPlanName").trigger('change');
    }
}

function _callBackReview(staffId){
    $("#staffId").val(staffId);
}

function _callBackOrg(orgId,orgName){
    $("#orgList").val(orgId);
}

function saveBidResultInfo(){
    var tenderInfoId=$("#tenderInfoId").val();
    var param={};
    var url="";
    if(tenderInfoId!='' && tenderInfoId!=null){
        url="/tenderPreparationService/updateResultInfo";
        param.tenderInfoId=tenderInfoId;
    }else{
        url="/tenderPreparationService/saveResultInfo";
    }
    var formValidator = $('#invitManageForm').data('bootstrapValidator');
    formValidator.validate();

    if (formValidator.isValid()) {
        param.impleProjId=$("#projectName").val();
        param.purchPlanId=$("#purchPlanName").val();
        var docId = $("#docId option:selected").attr("value");
        var docName = $("#docId option:selected").attr("text");
        if(docId==null || docId==""){
            toastr.error("请选择标书名");
            return;
        }
        if($("#purchPlanName").val()==""){
            param.tenderTitle=docId;
        }else{
            param.docManageId=docId;
            param.docManageName=docName;
        }

        param.evalPartyId=$("#staffId").val();
        param.openDt=$("#openDt").val();
        param.statusCd=$("#statusCd").val();
//   param.orgId=$("#orgList").val();
        param.remark=$("#description").val();
        var client = new com.im.common.ajax();
        var result = client.callAsJson(url,param);
        if(result.resultCode!=0){
            toastr.error(result.resultMsg);
        }else{
            $('#addEditModal').modal("hide").find('.modal-title').html('开标登记新增');
            queryBidResultInfo();
        }
    }
}

function _callBackProjectCondition(projectId,projectName){
    $("#belongPlan").val(projectId);
}

function queryBidResultInfo(){
    defaultParameter.projectId=$("#implProjectId").val().trim();
    defaultParameter.planProjClass=$("#planProjClass").val().trim();
//  defaultParameter.docName=$("#docName").val().trim();
    defaultParameter.orgId=$("#orgId").val();
    defaultParameter.statusCd=$("#purchaseStatusCd").val().trim();
    $('#tenderList').datagrid('load',defaultParameter);
}

function initStatus(){
    var client = new com.im.common.ajax();
    var param={};
    param.tabName="T_TENDER_INFO";
    param.colName="STATUS_CD";
    var result = client.callAsJson("commonService/queryTabColParam",param);
    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        result.result.unshift({'colVal':'','colValName':'全部'});
        $.each( result.result, function (i) {
            $('#statusCd').append("<option value=" + result.result[i].colVal + ">" +result.result[i].colValName + "</option>");
        });
        $("#statusCd").select2({});
    }
}





function reset(){
    $("#projuectOut").val('');
    $("#belongPlan").val('');
    $("#planProjClass").val('').trigger();
    $("#docName").val('');
}

function initOrg(){
    var client = new com.im.common.ajax();
    var result = client.callAsJson("userService/queryOrgarizationsByCond", {"forOrgList": "","orgType":10});

    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        console.log(result);
        result.result.unshift({'orgId':'','orgName':'全部'});
        $.each( result.result, function (i) {
            $('#orgId').append("<option value=" + result.result[i].orgId + ">" +result.result[i].orgName + "</option>");

        });
        $("#orgId").select2({});
    }
}

function formatValidator(){
    $("#invitManageForm").bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-loadData'
        },
        excluded: [':disabled'],
        fields: {
            /*
            projectName: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择项目'
                    }
                }
            },
            purchPlanName: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择采购计划'
                    }
                }
            },
            */
            docId: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择标书'
                    }
                }
            },
            staffId: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择参与人'
                    }
                }
            },
            openDt: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '开标时间不能为空'
                    }
                }
            },
            statusCd: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择状态'
                    }
                }
            },
//      orgList: {
//        trigger:"change",
//        validators: {
//          notEmpty: {
//            message: '请选择承接商'
//          }
//        }
//      },
        }
    });
}


/**
 * 获取标书列表，关联实施项目、采购计划
 */
function querySuccTendInfoListForOpenBid() {
    var client = new com.im.common.ajax();
    var result = client.callAsJson("tenderPreparationService/querySuccTendInfoListForOpenBid",null);
    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        succTendInfoList = result.result;
        resetSuccTendInfoList();
    }
}

function resetSuccTendInfoList() {
    $('#docId').children().remove();
    $('#projectName').children().remove();
    $('#purchPlanName').children().remove();

    if(succTendInfoList == null || succTendInfoList.length == 0) {
        $('#docId').append("<option value=''>无</option>");
        $('#projectName').append("<option value=''>无</option>");
        $('#purchPlanName').append("<option value=''>无</option>");
    } else {
        $.each(succTendInfoList, function (i) {
            $('#docId').append("<option index=" + i + " value=" + succTendInfoList[i].tenderInfoId + ">" + succTendInfoList[i].tenderTitle + "</option>");
        });

        $('#docId').change(function(){
            var index = $("#docId option:selected").attr("index");
            if(index == undefined) {
                return;
            }
            $('#projectName').children().remove();
            $('#purchPlanName').children().remove();

            if(succTendInfoList[index].impleProjId != null && succTendInfoList[index].impleProjId != "") {
                $('#projectName').append("<option value=" + succTendInfoList[index].impleProjId + ">" +succTendInfoList[index].impleProjName + "</option>");
            }else {
                $('#projectName').append("<option value=''>无</option>");
            }
            if(succTendInfoList[index].purchPlanId != null && succTendInfoList[index].purchPlanId != "") {
                $('#purchPlanName').append("<option value=" + succTendInfoList[index].purchPlanId + ">" +succTendInfoList[index].purchPlanName + "</option>");
            } else {
                $('#purchPlanName').append("<option value=''>无</option>");
            }
        });

        $('#docId').val(succTendInfoList[0].tenderInfoId).trigger("change");
    }

}
function initPurchaseStatusCd(){
    var client = new com.im.common.ajax();
    var param={};
    param.tabName="T_PURCHASE_PLAN";
    param.colName="STATUS_CD";
    var result = client.callAsJson("commonService/queryTabColParam",param);
    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        result.result.unshift({'colVal':'','colValName':'全部'});
        statusData=result.result;
        $.each( result.result, function (i) {
            $('#purchaseStatusCd').append("<option value=" + result.result[i].colVal + ">" +result.result[i].colValName + "</option>");
        });
        $("#purchaseStatusCd").select2({});
    }
}

$(function(){

//  initOrg();


    $("#orgId").project2unit2itemCommpent({
        //elmIdProjectSel : "projectSel",//规划工程下拉元素
        elmIdPlanTypeSel : "planProjClass",
        elmIdUnitSel : "orgId",//组织单位下拉元素
        elmIdItemSel : "implProjectId",//实施项目下拉元素
        orgType : "10",//初始化单位时，单位类型
        callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
            //_callBackOrg(objvalue, objname);
            //callBackType : 1 所属规划值变更 2单位值变更  3项目名称变更
            //ret: orgId,orgName,impleProjId,impleProjName,planProjClass,planProjClassName
            queryBidResultInfo();
        }
    });

    initTable();
    // $("#planProjClass").constantCommpent({
    //     elmIdSel : "planProjClass",//需要展示的位置下拉框
    //     constParamCode : "PLAN_PROJ_CLASS",//需要加载的常量编码
    //     callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
    //         queryBidResultInfo();
    //     }
    // });

    initStatus();
    // initPlan();

//  $("#itemBtn").click(function() {
//    $("#itemBtn").itemSearchCommpent({
//      elmIdOut : "projectNameText",//组织树单击之后回填的文本框（input）
//      elmIdModal : "itemSearchModal",//用户选择
//      elmIdOrgModal : "unitSearchModal",//组织查询
//      callbackFunc: function (projectId, projectName) {//组织树单击之后回调函数
//        _callBackProjectInfo(projectId, projectName);
//      }
//    });
//  });
//   $("#projectName").project2unit2itemCommpent({
//       elmIdPlanTypeSel : "",
//       elmIdUnitSel : "",//组织单位下拉元素
//       elmIdItemSel : "projectName",//实施项目下拉元素
//       orgType : "",//初始化单位时，单位类型
//       callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
//     	  _callBackProjectInfo(ret.impleProjId, ret.impleProjName);
//       }
//   });



    $("#userBtn1").click(function() {
        $("#userBtn1").userSearchMutilCommpent({
            elmIdModal : "userSearchModal",//用户查询模态框
            elmIdOut : "reviewer",//确认时文本回填
            multiCheck : true,//false单选 true多选
            checkList : [],//已经选择的用户列表，用户取消或者删除选择[{staffId : 1,staffName : 2}]
            callbackFunc: function(objlist) {
                var staffList="";
                for(var i=0;i<objlist.length;i++){
                    staffList=staffList+objlist[i].staffId+",";
                }
                _callBackReview(staffList);
            }
        });
    });
//  $("#userBtn1").click(function() {
//    $("#reviewer").userSearchCommpent({
//      elmIdOut : "reviewer",//组织树单击之后回填的文本框（input）
//      elmIdModal : "userSearchModal",//用户选择
//      elmIdOrgModal : "unitSearchModal",//组织查询
//      callbackFunc: function (staffId, staffName) {//组织树单击之后回调函数
//        _callBackReview(staffId, staffName);
//      }
//    });
//  });

//  $("#orgBtn1").click(function() {
//    $("#orgText").unitSearchCommpent({
//      elmIdOut : "orgText",//组织树单击之后回填的文本框（input）
//      elmIdModal : "unitSearchModal",
//      hasOrgType: true,//组织树是否先展示组织类型
//      callbackFunc: function (orgId, orgName) {//组织树单击之后回调函数
//        _callBackOrg(orgId, orgName);
//      }
//    });
//  });

    $("#saveBtn").click(function(){
        saveBidResultInfo();
    });

    $('#addEditModal').on('hidden.bs.modal', function () {
      $("#staffId").val("");
        $("#reviewer").val("");
      $("#statusCd").val("").trigger("change");
//      $("#orgList").val("");
      $("#tenderInfoId").val("");
      $('#invitManageForm').data('bootstrapValidator').options.excluded = [':disabled'];
      $('#invitManageForm').bootstrapValidator('resetForm', true);
      $('#invitManageForm')[0].reset();
        $("#invitManageForm").data('bootstrapValidator').destroy();
        $('#invitManageForm').data('bootstrapValidator', null);
        formatValidator();
        resetSuccTendInfoList();
        $('#addEditModal .modal-title').html('开标登记新增')
    });

//  $("#projectBtn").click(function() {
//    $("#projectBtn").itemSearchCommpent({
//      elmIdOut : "projuectOut",//组织树单击之后回填的文本框（input）
//      elmIdModal : "projectSearchModal",//用户选择
//      elmIdOrgModal : "unitSearchModal",//组织查询
//      callbackFunc: function (projectId, projectName) {//组织树单击之后回调函数
//        _callBackProjectCondition(projectId, projectName);
//        queryBidResultInfo();
//      }
//    });
//  });

    $("#btnQuery").click(function(){
        queryBidResultInfo();
    });

    $('#btn_reset').click(function (){
        $('#planProjClass').val('').trigger("change");
        $('#projuectOut').val('');
        $('#belongPlan').val('');
        $('#docName').val('');
        queryBidResultInfo();
    });

    $('.datetimepicker').datepicker({
        onSelect:function (){
            $('.datetimepicker').trigger("change");
        }
    });

    formatValidator();

    querySuccTendInfoListForOpenBid();

    initPurchaseStatusCd();

    $("#purchaseStatusCd").change(function(){
        queryBidResultInfo();
    });

})

